package com.wanmait.employment.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.employment.entity.Admin;
import com.wanmait.employment.service.AdminService;
import com.wanmait.employment.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JWTInterceptor implements HandlerInterceptor {
@Resource
    private AdminService adminService;
    //调用功能处理方法之前执行，返回true表示继续执行功能处理方法；返回false不执行功能处理方法，如果前后端不分离一般配合重定向，如果前后端分离一般就直接通过输出流返回响应数据
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是预检请求，通过
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //获得token 客户端请求头传递token
        String token = request.getHeader("token");
//        System.out.println("SDADSDS7786*************");
        if (token == null) {
            //会执行统一的异常处理,CommonControllerAdvice的processJWTVerificationException统一返回
            throw new JWTVerificationException("token不能为空8888");
        }
        //生成token时签发对象用的id
        Integer id = null;
        try {
            id = Integer.parseInt(JWTUtils.getAudience(token));
        } catch (NumberFormatException e) {
            throw new JWTVerificationException("token解析失败");
        }
        //获得管理员
        Admin admin = adminService.getById(id);
        if(admin==null){
            throw new JWTVerificationException("没查询到对应的用户");
        }
        //从redis中取出admin
//        Admin admin = (Admin) redisTemplate.opsForValue().get("token:"+token);
//        if(admin==null){
//            throw new JWTVerificationException("没查询到对应的用户");
//        }
        //验证token
        JWTUtils.verifyToken(token,admin.getAdminPass());

        request.setAttribute("admin",admin);
        return true;
    }

}
